/**
 * 
 * @Project le cOeur - Data Virtualization
 * @Date 08.12.2012
 * @Author Aebi Pascal, Kocher Marc
 * @School BFH-TI Biel, Bachelor Thesis
 *
 */

package main.api.http;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class represents a component defined by the HTTP protocol (RFC-2616).
 */
public class StatusLine extends StartLine {

	private String statusLine;
	private Version version;
	private StatusCode statusCode;
	private ReasonPhrase reasonPhrase;

	/**
	 * Creates a HTTP response status line from a given string.
	 * 
	 * @param statusLine The status line string containing the HTTP version, the HTTP status code and the HTTP reason phrase.
	 */
	public StatusLine(String statusLine) {
		this.statusLine = statusLine;
	}
	
	/**
	 * Creates a HTTP response status line.
	 * 
	 * @param version The HTTP version.
	 * @param statusCode The HTTP status code.
	 * @param reasonPhrase The HTTP reason phrase.
	 */
	public StatusLine(Version version, StatusCode statusCode, ReasonPhrase reasonPhrase){
		this.version = version;
		this.statusCode = statusCode;
		this.reasonPhrase = reasonPhrase;
	}
	
	@Override
	public void parse() {
		Pattern pattern = Pattern.compile("(HTTP/\\d.\\d)\\s(\\d{3})\\s(.+)");
		Matcher matcher = pattern.matcher(this.statusLine);
		matcher.find();
		this.version = Version.getFromValue(matcher.group(1));
		this.statusCode = StatusCode.getFromValue(Integer.parseInt(matcher.group(2)));
		this.reasonPhrase = ReasonPhrase.getFromValue(matcher.group(3));
	}

	@Override
	public String compose() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(this.version.getValue());
		stringBuilder.append(" ");
		stringBuilder.append(this.statusCode.getValue());
		stringBuilder.append(" ");
		stringBuilder.append(this.reasonPhrase.getValue());
		stringBuilder.append("\r\n");
		return stringBuilder.toString();
	}
	
	@Override
	public String toString() {
		return this.compose();
	}
	
	/**
	 * Returns the version of the status line header.
	 * 
	 * @return The HTTP version.
	 */
	public Version getVersion() {
		return this.version;
	}

	/**
	 * Returns the status code of the status line header.
	 * 
	 * @return The HTTP status code.
	 */
	public StatusCode getStatusCode() {
		return this.statusCode;
	}

	/**
	 * Returns the reason phrase of the status line header.
	 * 
	 * @return The HTTP reason phrase.
	 */
	public ReasonPhrase getReasonPhrase() {
		return this.reasonPhrase;
	}

}
